package com.nowcoder.community.service.impl;

import com.nowcoder.community.constant.UserConstant;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.constant.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.MailClient;
import com.nowcoder.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author 花木凋零成兰
 * @date 2024/3/4 21:26
 */
@Service
public class UserServiceImpl implements UserService  {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

//    @Autowired
//    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${community.path.domain}")
    private String domain;  // 注入项目域名

    @Value("${server.servlet.context-path}")
    private String contextPath; // 注入项目路径

    /**
     * 根据用户id 查询用户
     * @param id
     * @return
     */
    @Override
    public User findUserById(int id) {
        // return userMapper.selectById(id);
        // 先从缓存中查找用户
        User user = getCache(id);
        if (user == null) {
            user = initCache(id);
        }
        return user;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();

        // 空值判断处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }

        // 验证账号
        User selectUser = userMapper.selectByName(user.getUsername());  // 从数据库查询到的用户信息
        if (selectUser != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        // 验证邮箱
        selectUser = userMapper.selectByEmail(user.getEmail());
        if (selectUser != null) {
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }

        // 验证后 开始注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5)); // 设置加密的随机字符串salt
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));   // md5加密
        user.setType(0);    // 默认为普通用户
        user.setStatus(0);  // 默认未激活
        user.setActivationCode(CommunityUtil.generateUUID());   // 随机用户账号激活码
        //  随机头像
        user.setHeaderUrl(String.format("https://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        // 设置创建用户时间
        user.setCreateTime(new Date());
        userMapper.insertUser(user);    // 将用户数据保存到数据库中 且默认生成用户id

        // 发送激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        // http://localhost:8080/community/activation/userId/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);   // 加载邮件内容html

        mailClient.sendMail(user.getEmail(), "激活账户", content);  // 执行发送

        return map;
    }

    /**
     * 激活用户
     * @param userId
     * @param code
     * @return
     */
    @Override
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {
            return CommunityConstant.ACTIVATION_REPEAT; // 重复激活
        } else if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1); // 激活用户
            clearCache(userId);
            return CommunityConstant.ACTIVATION_SUCCESS; // 激活成功
        } else {
            return CommunityConstant.ACTIVATION_FAILURE; // 激活失败
        }
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @param expireSeconds
     * @return
     */
    @Override
    public Map<String, Object> login(String username, String password, int expireSeconds) {
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }

        // 验证账号
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }
        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }
        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = LoginTicket.builder()
                .userId(user.getId())
                .ticket(CommunityUtil.generateUUID())
                .status(0)
                .expired(new Date(System.currentTimeMillis() + expireSeconds * 1000L))
                .build();
        // loginTicketMapper.insertLoginTicket(loginTicket);

        // 将登录凭证 保存到Redis中
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey, loginTicket);

        map.put("ticket", loginTicket.getTicket());

        return map;
    }

    /**
     * 用户退出登录
     * @param ticket
     */
    @Override
    public void logout(String ticket) {
        // loginTicketMapper.updateStatus(ticket, 1);
        // 从Redis中 获取登录凭证
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }

    /**
     * 根据登录凭证查询 loginTicket
     * @param ticket
     * @return
     */
    public LoginTicket findLoginTicket(String ticket) {
        // return loginTicketMapper.selectByTicket(ticket);
        // 从Redis中 获取登录凭证
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 更新用户头像
     * @param userId
     * @param headerUrl
     * @return
     */
    public int updateHeader(int userId, String headerUrl) {
        int rows = userMapper.updateHeader(userId, headerUrl);
        clearCache(userId);
        return rows;
    }

    /**
     * 根据id修改用户密码
     * @param userId
     * @param password
     * @return
     */
    // @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int updatePassword(int userId, String password, String salt) {
        int rows = userMapper.updatePassword(userId, password);
        userMapper.updateSalt(userId, salt);
        clearCache(userId);
        return rows;
    }

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }

    // 1、优先从缓存中取值
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }
    // 2、取不到时初始化缓存数据
    private User initCache(int userId) {
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }


    // 3、数据变更时清除缓存数据
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

    /**
     * 获得用户权限
     * @param userId
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = this.findUserById(userId);
        // 保存权限集合
        List<GrantedAuthority> list = new ArrayList<>();

        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return UserConstant.AUTHORITY_ADMIN;
                    case 2:
                        return UserConstant.AUTHORITY_MODERATOR;
                    default:
                        return UserConstant.AUTHORITY_USER;
                }
            }
        });

        return list;
    }

}
